﻿using MQTT.Server.Host.Entity;
using MQTT.Server.Host.WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Http;
using MQTT.Server.Host.Controller;

namespace MQTT.Server.Host.WebAPI
{
    public class ValuesController : ApiController
    {
        /// <summary>
        /// 获取数据（温度、湿度、PM2.5、PM10）
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("getdata")]
        public ApiResponse GetData(int deviceId)
        {
            ApiResponse response = new ApiResponse();

            DeviceEntity device = DataController.GetDevice(deviceId);
            if (device == null)
            {
                response.Code = ResponseCode.Error;
                response.Msg = "device not exist";
                return response;
            }
            // 根据设备id和数据点标识获取所有的最新数据
            var deviceDataTags = DataController.GetDeviceDataTags(deviceId);
            List<DataNodeEntity> nodes = new List<DataNodeEntity>();
            foreach (var type in deviceDataTags)
            {
                if (type.DataTypeId > 4)
                {
                    continue;
                }

                switch (type.DataTypeId)
                {
                    case 1:
                        DataNodeEntity dataTemp = DataController.GetDataNode(deviceId, type.Tag);
                        if (dataTemp != null)
                        {
                            dataTemp.Tag = "temp";
                            nodes.Add(dataTemp);
                        }
                        break;
                    case 2:
                        DataNodeEntity dataHum = DataController.GetDataNode(deviceId, type.Tag);
                        if (dataHum != null)
                        {
                            dataHum.Tag = "hum";
                            nodes.Add(dataHum);
                        }

                        break;
                    case 3:
                        DataNodeEntity datapm25 = DataController.GetDataNode(deviceId, type.Tag);
                        if (datapm25 != null)
                        {
                            datapm25.Tag = "pm25";
                            nodes.Add(datapm25);
                        }
                        break;
                    case 4:
                        DataNodeEntity datapm10 = DataController.GetDataNode(deviceId, type.Tag);
                        if (datapm10 != null)
                        {
                            datapm10.Tag = "pm10";
                            nodes.Add(datapm10);
                        }
                        break;
                }
            }

            response.Code = ResponseCode.Success;
            response.Data = nodes;
            return response;
        }


        /// <summary>
        /// 获取最新数据
        /// </summary>
        /// <param name="deviceId">设备id（不可空）</param>
        /// <param name="dataNodeTag">数据点标识（可空；空：获取该设备下所有数据点最新数据；不空：获取该设备该数据点最新数据）</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("news")]
        public ApiResponse News(int deviceId, string dataNodeTag = null)
        {
            ApiResponse response = new ApiResponse();
            // 判断数据点标识是否为空

            DeviceEntity device = DataController.GetDevice(deviceId);
            if (device == null)
            {
                response.Code = ResponseCode.Error;
                response.Msg = "device not exist";
                return response;
            }
            // 获取设备信息

            // 判断datanodetag是否为null
            if (string.IsNullOrEmpty(dataNodeTag))
            {
                var dataNodes = DataController.GetDataNodes(deviceId);
                if (dataNodes.Count == 0)
                {
                    response.Code = ResponseCode.Error;
                    response.Msg = "no data points associated with this device";
                }
                else
                {
                    device.DataNodes = dataNodes;
                    response.Code = ResponseCode.Success;
                    response.Data = device;
                }

            }
            else
            {
                List<DataNodeEntity> nodes = new List<DataNodeEntity>();
                // 查询指定的tag
                DataNodeEntity dataNodeEntity = DataController.GetDataNode(deviceId, dataNodeTag);
                if (dataNodeEntity == null)
                {
                    response.Code = ResponseCode.Error;
                    response.Msg = "device tag not exist";
                }
                else
                {
                    nodes.Add(dataNodeEntity);
                    device.DataNodes = nodes;
                    response.Code = ResponseCode.Success;
                    response.Data = device;
                }
            }
            return response;

        }

        /// <summary>
        /// 获取历史数据
        /// </summary>
        /// <param name="deviceId">设备id（不可空）</param>
        /// <param name="dataNodeTag">数据点标识（不可空）</param>
        /// <param name="startTime">开始时间（不可空，格式：2020-08-08 18:22:30）</param>
        /// <param name="endTime">结束时间（可空）</param>
        /// <param name="count">数量（可空）</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("history")]
        public ApiResponse History(int deviceId, string dataNodeTag, string startTime, string endTime = null, int count = 0)
        {
            ApiResponse response = new ApiResponse();
            response.Code = ResponseCode.Success;
            // 获取设备
            DeviceEntity device = DataController.GetDevice(deviceId);
            if (device == null)
            {
                response.Code = ResponseCode.Error;
                response.Msg = "device not exist";
                return response;
            }

            // 判断结束时间是否为空
            if (string.IsNullOrEmpty(endTime))
            {
                endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }

            string sql = $"SELECT DataHistory.Value, DataHistory.Time, DataType.Unit, DeviceDataTag.Tag " +
                         $"FROM DataType " +
                         $"INNER JOIN DeviceDataTag " +
                         $"ON DataType.Id = DeviceDataTag.DataTypeId " +
                         $"INNER JOIN DataHistory " +
                         $"ON DataHistory.DeviceDataTagId = DeviceDataTag.Id " +
                         $"WHERE DeviceDataTag.Tag = '{dataNodeTag}' " +
                         $"AND DataHistory.Time BETWEEN '{startTime}' AND '{endTime}' " +
                         $"ORDER BY DataHistory.Time DESC";
            if (count != 0)
            {
                sql += $" LIMIT {count}";
            }

            var dataTable = App.OperateSql.GetTable(sql);
            List<DataNodeEntity> nodes = new List<DataNodeEntity>();
            foreach (DataRow row in dataTable.Rows)
            {
                DataNodeEntity dataNodeEntity = DataController.GetDataNode(row);
                nodes.Add(dataNodeEntity);
            }

            if (nodes.Count > 0)
            {
                device.DataNodes = nodes;
                response.Data = device;
            }
            return response;
        }
    }
}
